<template>
    <div>
        <div ref="chartRef" style="width: 100%; height: 500px;"></div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import request from '@/utils/request';

const chartRef = ref(null);
let myChart = null;

// 定义获取商品统计数据的函数
const getGoodsStats = async () => {
    try {
        const res = await request.get('/stats/goods');
        if (res.code === 0) {
            const { date, source } = res.data;
            const legendData = source.map(item => item.type);
            const seriesData = source.map(item => ({
                name: item.type,
                type: 'line',
                stack: 'Total',
                data: item.data
            }));

            const option = {
                title: {
                    text: '商品销售统计'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: legendData
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: date
                },
                yAxis: {
                    type: 'value'
                },
                series: seriesData
            };

            if (myChart) {
                myChart.setOption(option);
            }
        }
    } catch (error) {
        console.error('获取商品统计数据失败:', error);
    }
};

onMounted(() => {
    // 初始化图表
    if (chartRef.value) {
        myChart = echarts.init(chartRef.value);

        // 处理窗口大小变化
        window.addEventListener('resize', handleResize);

        // 获取商品统计数据
        getGoodsStats();
    }
});

const handleResize = () => {
    if (myChart) {
        myChart.resize();
    }
};

onBeforeUnmount(() => {
    // 组件卸载时清理资源
    if (myChart) {
        window.removeEventListener('resize', handleResize);
        myChart.dispose();
        myChart = null;
    }
});
</script>

<style scoped>
</style>    